package com.github.iogogogo.core.filter;

import com.github.iogogogo.Version;
import com.github.iogogogo.common.conf.GitConf;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * Created by tao.zeng on 2021/3/17.
 */
@Slf4j
@Component
public class ResponseFilter implements Filter {

    @Autowired
    private GitConf gitConf;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (servletResponse instanceof HttpServletResponse) {
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            setHeader(response);
            filterChain.doFilter(servletRequest, response);
        }
    }

    private String convert(String text) {
        return new String(text.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
    }


    private void setHeader(HttpServletResponse response) {
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        // git build info
        response.setHeader("git-commit-id", gitConf.getCommitId());
        response.setHeader("git-branch", gitConf.getBranch());
        response.setHeader("git-commit-time", gitConf.getCommitTime());
        response.setHeader("git-build-time", gitConf.getBuildTime());
        response.setHeader("git-build-version", gitConf.getBuildVersion());
        response.setHeader("git-tag-name", gitConf.getTagName());
        response.setHeader("git-commit-message-full", convert(gitConf.getCommitMessageFull()));
        response.setHeader("git-commit-message-short", convert(gitConf.getCommitMessageShort()));
        response.setHeader("git.build.user.name", gitConf.getBuildUser());
        response.setHeader("git.build.host", gitConf.getBuildHost());
        response.setHeader("git.commit.user.name", gitConf.getCommitUser());
        response.setHeader("git.remote.origin.url", gitConf.getRemoteUrl());

        // project build info
        response.setHeader("data-quality-build-version", Version.VERSION);
        response.setHeader("data-quality-build-time", Version.TIMESTAMP);
        response.setHeader("data-quality-build-description", Version.DESCRIPTION);
        response.setHeader("data-quality-build-artifactid", Version.ARTIFACTID);
    }
}
